package com.msh.automatic.android.control.util

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK
import android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_HOME
import android.accessibilityservice.GestureDescription
import android.content.Intent
import android.graphics.Rect
import android.view.accessibility.AccessibilityNodeInfo
import com.msh.automatic.android.control.service.AIAccessibilityService
import kotlinx.coroutines.delay
import kotlin.random.Random

object AccessibilityServiceUtil {

    suspend fun goHome(service: AIAccessibilityService){
        for (i in 0..3) {
            service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK)
            delay(1_000)  // 1秒
            if(service.currentPackage.equals("com.msh.automatic.android.control")){
                return
            }
            if(
                service.currentPackage.equals("com.miui.home")
                && service.currentActivity.equals("com.miui.home.launcher.Launcher")
            ){
                break
            }
        }

        service.performGlobalAction(GLOBAL_ACTION_HOME)
        delay(3_000)  // 30秒

        service.performGlobalAction(
            GLOBAL_ACTION_BACK
        )
        delay(3_000)  // 30秒
        launchAppByName(service,"美数合智能助手")
    }
    suspend fun waitActivity(service: AIAccessibilityService,packageName:String, activityName:String, i:Int):Boolean{
        for (i in 0..i) {
            // i: 0, 1, 2, 3
            if(service.currentPackage.equals(packageName)  && service.currentActivity.equals(activityName)){
                delay(2_000)  // 30秒
                return true
            }
            delay(10_000)  // 30秒
        }
        return false
    }
    fun launchAppByName(service: AIAccessibilityService,appName: String): Boolean {
        val rootNode = service.getCurrentRootNode()

        // 广度优先遍历节点
        val queue = ArrayDeque<AccessibilityNodeInfo>()
        queue.add(rootNode)

        while (queue.isNotEmpty()) {
            val node = queue.removeFirst()

            // 匹配文本（桌面图标通常是TextView，text是App名称）
            if (node.text != null && node.text.toString().equals(appName, ignoreCase = true)) {
                if (node.isClickable) {
                    node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                    return true
                } else {
                    // 尝试往上找可点击的父节点
                    var parent = node.parent
                    while (parent != null) {
                        if (parent.isClickable) {
                            parent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                            return true
                        }
                        parent = parent.parent
                    }
                }
            }

            // 遍历子节点
            for (i in 0 until node.childCount) {
                node.getChild(i)?.let { queue.add(it) }
            }
        }

        return false // 没有找到
    }

    suspend fun findAccessibilityNodeInfosByText(service: AIAccessibilityService,text:String):List<AccessibilityNodeInfo>{
        for (i in 0..3) {
            var nodes = service.getCurrentRootNode().findAccessibilityNodeInfosByText(text)
            if(nodes.size != 0){
                return nodes
            }
            delay(10_000)  // 30秒
        }
        return emptyList()
    }
    suspend fun clickByText(service: AIAccessibilityService,text:String):Boolean{
        var nodes = findAccessibilityNodeInfosByText(service,text)
        if(nodes.isEmpty()){
            return false
        }
        val node =nodes.get(0)
        clickByNode(service,node)
        return true
    }

    suspend fun clickByNode(service: AIAccessibilityService,node:AccessibilityNodeInfo):Boolean{
        val rect = Rect()
        node.getBoundsInScreen(rect)
        val random = Random(System.currentTimeMillis())
        val x = rect.left + random.nextInt(rect.width())
        val y = rect.top + random.nextInt(rect.height())
        click(service,x,y)
        return true
    }
    fun click(service: AIAccessibilityService,x: Int, y: Int) {
        val path = android.graphics.Path().apply {
            moveTo(x.toFloat(), y.toFloat())
        }

        val gesture = GestureDescription.Builder()
            .addStroke(GestureDescription.StrokeDescription(path, 0, 30L +Random(System.currentTimeMillis()).nextLong(50)))
            .build()

        service.dispatchGesture(gesture, null, null)
    }
}